import { RegisterModel } from '../db/models/user'
import { createUser, getUserInfo } from '../services/auth'
import errorInfo from '../constants/errorInfo'
import { ErrorResponse, SuccessResponse } from '../utils/Response'
import { createMD5 } from '../utils/createMD5'
import { createToken } from '../utils/token'

const { registerUserNameExistInfo, registerFailInfo, loginFailInfo } = errorInfo

interface LoginModel {
  username: string,
  password: string
}

/**
 * @author lihh
 * @description 进行用户注册controller
 * @param params
 */
export const registerController = async (params: RegisterModel) => {
  const { username, password } = params
  /* 判断用户是否注册 */
  const userInfo = await getUserInfo({ username })
  if ( userInfo ) {
    const { code, message } = registerUserNameExistInfo
    return new ErrorResponse(code, message)
  }

  /* 注册用户 */
  try {
    await createUser({
      ...params,
      password: createMD5(password)
    })
    return new SuccessResponse({})
  } catch ( err ) {
    const { code, message } = registerFailInfo
    return new ErrorResponse(code, message)
  }
}

/**
 * @author lihh
 * @description 用户登录的controller
 * @param params 表示用户传递的参数
 */
export const loginController = async (params: LoginModel) => {
  const { username, password } = params
  /* 用来获取用户信息 */
  const userInfo = await getUserInfo({ username, password })
  if ( userInfo ) {
    const { id, username } = userInfo,
      token = createToken({ id, username })
    return new SuccessResponse({ token })
  }

  /* 获取不到 返回登录失败 */
  const { code, message } = loginFailInfo
  return new ErrorResponse(code, message)
}
